package com.example.fbsmobile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.fbsmobile.util.SessionInfo;

public class MainActivity extends Activity implements OnClickListener {
	
	private Button logInButton;
	private EditText usernameEditText;
	private EditText passwordEditText;
	private static final String url = "http://10.10.2.144:8080/FBS.Team7/AndroidLogin";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		usernameEditText = (EditText) findViewById(R.id.usernameEditText);
		passwordEditText = (EditText) findViewById(R.id.passwordEditText);
		logInButton = (Button) findViewById(R.id.logInButton);
		logInButton.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();				
		if (networkInfo != null && networkInfo.isConnected()) {
			new DownloadWebpageText().execute(url);
		} else {
			CharSequence text = "No network connection LAH!";
			int duration = Toast.LENGTH_SHORT;
			Toast toast = Toast.makeText(this, text, duration);
			toast.show();
		}
	}

	//Asynchronous job
	private class DownloadWebpageText extends AsyncTask<String, Integer, String> {

		@Override
		protected String doInBackground(String... urls) {
			String result = downloadUrl(urls[0]);
			return result;
		}
			     
		@Override
		protected void onPostExecute(String result) {
			if(!result.matches("error")){
				//Store user details in a private file
				SessionInfo sessionInfo = new SessionInfo(MainActivity.this);
				sessionInfo.toWrite(result);
				
				//Call BookingStatusActivity by default
				Intent i = new Intent(MainActivity.this,BookingStatusActivity.class);
				startActivity(i);
			} else
			{
				CharSequence text = "Oops wrong credentials!";
				int duration = Toast.LENGTH_SHORT;
				Toast toast = Toast.makeText(MainActivity.this, text, duration);
				toast.show();
			}

		}

		//Make the connection with the servlet
		private String downloadUrl(String myurl) {
			String result = "error";
			
			try {	
				List<NameValuePair> formparams = new ArrayList<NameValuePair>();
				formparams.add(new BasicNameValuePair("username", usernameEditText.getText().toString()));
				formparams.add(new BasicNameValuePair("password", passwordEditText.getText().toString()));

				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
				HttpPost httppost = new HttpPost(myurl);
				httppost.setEntity(entity);
				
				HttpResponse response = new DefaultHttpClient().execute(httppost);
				InputStream inp = response.getEntity().getContent();
				result = readIt(inp);
			} catch(Exception e){
				e.printStackTrace();
			}
			
			return result;
		}

		// Reads an InputStream and converts it to a String.
		private String readIt(InputStream stream) {
			BufferedReader rd = new BufferedReader(new InputStreamReader(stream));
			StringBuilder sb = new StringBuilder();
			String line;
			try {
				if((line = rd.readLine()).matches("true")){
					
					sb.append(line);
					sb.append("\n");
					sb.append(rd.readLine());
					sb.append("\n");
					sb.append(rd.readLine());
				}
				else{
					line = "error";
					sb.append(line);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			return sb.toString();			
		}
	}

}
